﻿package  core.net.socket{
	
	import flash.net.Socket;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class SocketClient extends EventDispatcher {
		
		
		private static var instance:SocketClient = new SocketClient();
		
		public static function getInstance():SocketClient{
			return instance;
		}
		
		
		
		private var sock:Socket;
		
		public function SocketClient() {
			this.sock = new Socket();
			this.sock.addEventListener(Event.CONNECT,onConnected);
			this.sock.addEventListener(IOErrorEvent.IO_ERROR ,onIoError);
			this.sock.addEventListener(Event.CLOSE,onClosed);
			this.sock.addEventListener(ProgressEvent.SOCKET_DATA,onSocketData);
		}
		
		
		private function onIoError(e:IOErrorEvent):void{
			//trace("SocketClient onIoError:" + e.toString());
			dispatchEvent(e);
		}
		
		private function onClosed(e:Event):void{
			//trace("SocketClient onClosed");
			dispatchEvent(e);
		}
		
		private function onConnected(e:Event):void{
			//trace("SocketClient onConnected");
			dispatchEvent(e);
		}
		
		private function onSocketData(e:ProgressEvent):void{
			//var str:String = this.sock.readUTFBytes(this.sock.bytesAvailable);
			//trace(str);
			dispatchEvent(e);
		}
		
		
		public function connectTo(ip:String,port:int):void{
			this.sock.connect(ip,port);
		}
		
		
		public function send(content:String):void{
			this.sock.writeUTFBytes(content);
			this.sock.flush();
		}
		
		public function read():String{
			return this.sock.readUTFBytes(this.sock.bytesAvailable);
		}
	}
	
}
